package com.gmail.hh.flickrj.sample.android.fragments;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.gmail.hh.flickrj.sample.android.FlickrjMainActivity;
import com.gmail.hh.flickrj.sample.android.R;
import com.gmail.hh.flickrj.sample.android.data.PhotoData;
import com.gmail.hh.flickrj.sample.android.interfaces.IPhotoSelectedListener;
import com.gmail.hh.flickrj.sample.android.listener.ImageViewZoomListener;


@SuppressLint("NewApi")
public class FragmentGallery1 extends Fragment  {

	private static final Logger logger = LoggerFactory.getLogger(FlickrjMainActivity.class);

	public static final String TAG = "fragment_gallery1";

private static Uri[] mUrls = null;
private static String[] strUrls = null;
private String[] mNames = null;
private GridView gridview = null;
private Cursor cc = null;
private Button btnMoreInfo = null;
private ProgressDialog myProgressDialog = null;
private Activity mActivity = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    mActivity=activity;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup vg, Bundle data) {
	// Inflate the  layout file.
	View view = inflater.inflate(R.layout.fragment_gallery1, null);

    btnMoreInfo = (Button) view.findViewById(R.id.btnMoreInfo);
    // It have to be matched with the directory in SDCard
    cc = mActivity.getContentResolver().query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null,
            null);

    // File[] files=f.listFiles();
    if (cc != null) {

        myProgressDialog = new ProgressDialog(mActivity);
        myProgressDialog.setMessage("Medien werden geladen");
        //myProgressDialog.setIcon(R.drawable.blind);
        myProgressDialog.show();

        new Thread() {
            public void run() {
                try {
                    cc.moveToFirst();
                    mUrls = new Uri[cc.getCount()];
                    strUrls = new String[cc.getCount()];
                    mNames = new String[cc.getCount()];
                    for (int i = 0; i < cc.getCount(); i++) {
                        cc.moveToPosition(i);
                        mUrls[i] = Uri.parse(cc.getString(1));
                        strUrls[i] = cc.getString(1);
                        mNames[i] = cc.getString(3);
                        //Log.e("mNames[i]",mNames[i]+":"+cc.getColumnCount()+ " : " +cc.getString(3));
                    }

                } catch (Exception e) {
                }
                myProgressDialog.dismiss();
            }
        }.start();
        
    gridview = (GridView) view.findViewById(R.id.gridview);
    ImageAdapterGall adapter = new ImageAdapterGall(mActivity);
    gridview.setAdapter(adapter);

//    gridview.setOnItemClickListener(new OnItemClickListener() {
//        public void onItemClick(AdapterView<?> parent, View v,
//                int position, long id) {
//            Intent i = new Intent(GalleryPage.this, BigImage.class);
//            logger.error("intent : " + ""+position);
//            i.putExtra("imgUrls", strUrls);
//            i.putExtra("position", position);
//            startActivity(i);
//        }
//    });

    }

    btnMoreInfo.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
    //        Intent i = new Intent(GalleryPage.this, ChildLogin.class);
    //        startActivity(i);
        }
    });
    
    return view;
}

/**
 * This class loads the image gallery in grid view.
 *
 */
public class ImageAdapterGall extends BaseAdapter {
    private Context mContext;

    public ImageAdapterGall(Context c) {
        mContext = c;
    }

    public int getCount() {
        return cc.getCount();
    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        LayoutInflater vi = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = vi.inflate(R.layout.photogrid_box, null);

        try {

            ImageView imageView = (ImageView) v.findViewById(R.id.imageIcon);
            //imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            // imageView.setPadding(8, 8, 8, 8);
            Bitmap bmp = decodeURI(mUrls[position].getPath());
            //BitmapFactory.decodeFile(mUrls[position].getPath());
            imageView.setImageBitmap(bmp);
            //bmp.
            TextView txtName = (TextView) v.findViewById(R.id.TextView01);
            txtName.setText(mNames[position]);
        } catch (Exception e) {

        }
        return v;
    }
}

@Override
public void onStart() {
    // TODO Auto-generated method stub
    super.onStart();
  //  FlurryAgent.onStartSession(this, "LPJJF9WYENDWYXXTEUDM");
}
// @Override
// protected void onStop() {
// TODO Auto-generated method stub
// super.onStop();
// FlurryAgent.onEndSession(this);

// }

/**
 * This method is to scale down the image 
 */
public Bitmap decodeURI(String filePath){

    Options options = new Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, options);

    // Only scale if we need to 
    // (16384 buffer for img processing)
    Boolean scaleByHeight = Math.abs(options.outHeight - 100) >= Math.abs(options.outWidth - 100);
    if(options.outHeight * options.outWidth * 2 >= 16384){
        // Load, scaling to smallest power of 2 that'll get it <= desired dimensions
        double sampleSize = scaleByHeight
            ? options.outHeight / 100
            : options.outWidth / 100;
        options.inSampleSize = 
            (int)Math.pow(2d, Math.floor(
            Math.log(sampleSize)/Math.log(2d)));
    }

    // Do the actual decoding
    options.inJustDecodeBounds = false;
    options.inTempStorage = new byte[512];  
    Bitmap output = BitmapFactory.decodeFile(filePath, options);

    return output;
}

	

	


}
